package com.jb.repair.acticity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;

import com.jb.repair.R;
import com.jb.repair.adapter.CheckRegisParentAdapter;
import com.jb.repair.dao.QueryDb;
import com.jb.repair.model.DeviceModel;
import com.jb.repair.util.MessageUtil;
import com.jb.repair.view.TitleView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by gaobin on 2015/10/30.
 */
public class CheckRegisActivity extends BaseActivity {
    private TitleView titleView;
    private static ListView lv_data;

    private static CheckRegisParentAdapter parentAdapter;
    public static List<DeviceModel> mData;
    private List<String> equipNameList = new ArrayList<>();  //存放所有设备的名称
    public String posId;
    public String posName;
    public Context context;
    private SharedPreferences sp;
    public static Boolean changable;
    private Boolean authority = false;  //批量处理权限，默认不可批量处理
    private QueryDb queryDb;
    private int index = 0;
    private int index_pre = 0;
    private boolean jumpFromTag;   // 是否是扫码后跳转来的
    private static final String TAG = "CheckRegisActivity";

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            parentAdapter.mData = mData;
            parentAdapter.notifyDataSetChanged();
            switch (msg.what) {
                case 1:
                    break;
                case 2:
                    MessageUtil.dismissProgressDialog();
                    break;
                case 3:
                    MessageUtil.dismissProgressDialog();
                    MessageUtil.showToast(CheckRegisActivity.this, "当前任务下无此位置");
                    finish();
                    break;
                case 0:
                    MessageUtil.dismissProgressDialog();
                    Boolean b = (Boolean) msg.obj;
                    if (!b)
                        lv_data.setSelection(0);
                    else
                        lv_data.setSelection(1);
            }
        }
    };

    @Override
    protected void onResume() {
        Log.i(TAG,"onResume");
        super.onResume();
        index = 0;
        index_pre = 0;
        mData.clear();
        MessageUtil.showProgressDialog(CheckRegisActivity.this, "正在加载");
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    DeviceModel model0 = queryDb.getPosDeviceModel(CheckLocActivity.task_id, posId, 0, index);
                    DeviceModel model1 = queryDb.getPosDeviceModel(CheckLocActivity.task_id, posId, 0, ++index);
                    DeviceModel model2 = queryDb.getPosDeviceModel(CheckLocActivity.task_id, posId, 0, ++index);
                    if (model0 == null) {
                        handler.sendEmptyMessage(3);
                        return;
                    }
                    mData.add(model0);
                    if (model1 != null) {
                        mData.add(model1);
                    }
                    if (model2 != null) {
                        mData.add(model2);
                    }
                    handler.sendEmptyMessage(2);
                }catch (Exception e){

                }
            }
        }.start();

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_check_regis);
        mData = new ArrayList<DeviceModel>();
        queryDb = QueryDb.getInstance(getApplicationContext());
        posId = getIntent().getStringExtra("posId");
        posName = QueryDb.getInstance(getApplicationContext()).getName("place", "TB_SI_TASK_RESULT", "place_id", posId);

        // 设定，是否是通过扫NFC或者二维码进入此页面的
        jumpFromTag = getIntent().getBooleanExtra("jumpFromTag", false);
        initView();
        authority = QueryDb.getInstance(getApplicationContext()).getAuthority();

        titleView.setTitle(posName);
        parentAdapter = new CheckRegisParentAdapter(this, mData, false, jumpFromTag);
        lv_data.setAdapter(parentAdapter);
        lv_data.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                switch (scrollState) {
                    // 当不滚动时
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                        // 判断滚动到底部
                        if (view.getLastVisiblePosition() == (view.getCount() - 1)) {
                            DeviceModel model = queryDb.getPosDeviceModel(CheckLocActivity.task_id, posId, 0, ++index);
                            if (model != null) {
                                mData.add(model);
                                parentAdapter.notifyDataSetChanged();
                            }
                        } else if (view.getFirstVisiblePosition() == 0) {
                            DeviceModel model = queryDb.getPosDeviceModelPre(CheckLocActivity.task_id, posId, 0, --index_pre);
                            if (model != null)
                                mData.add(0, model);
                            parentAdapter.notifyDataSetChanged();
                        }
                        break;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {
            }
        });
    }

    private void initView() {
        titleView = (TitleView) findViewById(R.id.titleView);
        lv_data = (ListView) findViewById(R.id.lv_data);

        titleView.setOnClickListener(new TitleView.OnTitleViewClickListener() {
            @Override
            public void onLeftImageClick(View view) {
                super.onLeftImageClick(view);
                CheckLocActivity.is_back = true;
                finish();
            }

            @Override
            public void onRightImage1Click(View view) {
                super.onRightImage1Click(view);
                showPop(view);

            }
        });
    }

    private void showPop2(View v) {
        ListView lv_equip = new ListView(this);
        if (equipNameList.size() == 0)
            equipNameList = queryDb.getAllEqName(CheckLocActivity.task_id, posId);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.textview_pop_list, equipNameList);
        lv_equip.setAdapter(adapter);
        final PopupWindow popupWindow = new PopupWindow(lv_equip, 200, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setFocusable(true);
        ColorDrawable dw = new ColorDrawable(0x00000000);
        popupWindow.setBackgroundDrawable(dw);
        popupWindow.showAsDropDown(v);

        lv_equip.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                if (mData.size() < equipNameList.size()) {
                    MessageUtil.showProgressDialog(CheckRegisActivity.this, "正在定位");
                    new Thread() {
                        @Override
                        public void run() {
                            super.run();
                            mData.clear();
                            List<DeviceModel> list = queryDb.getPosDeviceModelForLoc(CheckLocActivity.task_id, posId, 0, position);
                            mData.addAll(list);
                            Message msg = new Message();
                            if (position == 0) {
                                msg.obj = false;
                                index_pre = 0;
                                index = position + 2;
                            } else {
                                msg.obj = true;
                                index_pre = position - 1;
                                index = position + 1;
                            }
                            msg.what = 0;
                            handler.sendMessage(msg);
                        }
                    }.start();
                } else {
                    lv_data.setSelection(position);
                }
                popupWindow.dismiss();
            }
        });
    }


    private void showPop(final View view) {
        View popView = LayoutInflater.from(this).inflate(R.layout.pop_check_regis, null);
        final PopupWindow popupWindow = new PopupWindow(popView, 200, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setFocusable(true);
        ColorDrawable dw = new ColorDrawable(0x00000000);
        popupWindow.setBackgroundDrawable(dw);
        popupWindow.showAsDropDown(view);
        popView.findViewById(R.id.ll_loc_equip).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                showPop2(view);
            }
        });

        if (!authority) {
            popView.findViewById(R.id.ll_batch_regis).setVisibility(View.GONE);
        }

        //历史点检任务没有批量处理
        if (!changable) {
            popView.findViewById(R.id.ll_batch_regis).setVisibility(View.GONE);
        }
        popView.findViewById(R.id.ll_batch_regis).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                Intent intent = new Intent(getApplicationContext(), BatchDealActivity.class);
                intent.putExtra("jumpFromTag", jumpFromTag);
                jumpFromTag = false;
                intent.putExtra("posId", posId);
                intent.putExtra("posName", posName);
                startActivity(intent);
                popupWindow.dismiss();
                CheckRegisActivity.this.finish();

            }
        });
    }

    public static void update(final int position, final int childPosition, final int cycle, final String result) {
        switch (cycle) {
            case 0:
                mData.get(position).todayCheckList.get(childPosition).checkResult = result;
                break;
            case 1:
                mData.get(position).weekCheckList.get(childPosition).checkResult = result;
                break;
            case 2:
                mData.get(position).monthCheckList.get(childPosition).checkResult = result;
                break;
            case 3:
                mData.get(position).twiceWeekCheckList.get(childPosition).checkResult = result;
                break;
            case 4:
                mData.get(position).thirdWeekCheckList.get(childPosition).checkResult = result;
                break;
            case 5:
                mData.get(position).twiceMonthCheckList.get(childPosition).checkResult = result;
                break;
        }
        parentAdapter.mData = mData;
        parentAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MessageUtil.dismissProgressDialog();
        mData = null;
        index = 0;
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        CheckLocActivity.is_back = true;
        finish();
    }
}
